/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.localdb;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

/**
 *
 * @author Owner
 */
public class XMLParser {

    public XMLParser() {
    }

    public String parse(String confUrlPath) {
        String path = null;
        try {
           StringBuffer data = this.getConfigData(confUrlPath);
            ByteArrayInputStream objBAInputStream = new java.io.ByteArrayInputStream(data.toString().getBytes());
            InputSource ojbInputSource = new InputSource(objBAInputStream);
            Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(ojbInputSource);
            NodeList nodes = doc.getDocumentElement().getElementsByTagName("data");
            for (int i = 0; i < nodes.getLength(); i++) {
                Element element = (Element) nodes.item(i);
                path = element.getElementsByTagName("dbpath").item(0).getTextContent();
            }            
        } catch (ParserConfigurationException ex) {
            ex.printStackTrace();
        } catch (SAXException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return path;
    }
    
    public StringBuffer getConfigData(String filepath) {
        StringBuffer buff = new StringBuffer();
        BufferedReader br = null;
        try {
            File file = new File(filepath);
            if (file.exists()) {
                br = new BufferedReader(new FileReader(file));
                boolean endOfFile = false;
                String fragment = "";
                while (!endOfFile) {
                    fragment = br.readLine();
                    if (fragment == null) {
                        endOfFile = true;
                    } else {
                        buff.append(fragment);
                    }
                }
                br.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        //System.out.println("Buffer Data: " + buff);
        return buff;
    }
}
